#include <stdio.h>

// Context so users can supply their own malloc and log file descriptor.

typedef void* (*MallocFunc)(size_t);

typedef struct TnetContext_s {
  MallocFunc malloc;
  FILE* logfd;  // log to this descriptor.  if -1, don't log?
} TnetContext;

// A binary string that points at memory owned by others.
typedef struct Buffer_s {
  char* data;
  size_t len;  // length of data
} Buffer;

typedef struct Chunk_s {
  Buffer payload;  // shared memory with original string
  char tag;  // , } etc
} Chunk;

// Linked list of pairs of Chunks for parsing
typedef struct Pair_s {
  Chunk key;
  Chunk value;
  struct Pair_s* next;
} Pair;


// Helpers
//
size_t tnet_print_buf(Buffer b, FILE* f);
void tnet_print_pairs(Pair* p, FILE* f);
Chunk tnet_string_to_chunk(char* s);
int tnet_pairs_getchunk(Pair* p, const char* name, Chunk* c);
int tnet_chunk_equals_string(Chunk c, const char* s);

// Cleanup

void tnet_free_buffer(Buffer b);
void tnet_free_chunk(Chunk c);
void tnet_free_pairs(Pair* p);

//int parse_chunk_prefix(TnetContext* ctx, Buffer* buf, Chunk* chunk, char** pp);

// Main API

int tnet_parse_dict_chunks(TnetContext* ctx, Buffer buf, Pair** pairs);
int tnet_dump_dict(TnetContext* ctx, Pair* pairs, Buffer* out);
int tnet_read(TnetContext* ctx, FILE* f, Chunk* c);
